package org.amos.gateway.handler;

import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

/**
 * @desc: sentinel控制台配置持久化到nacos
 * @author: liubt
 * @date: 2020-12-19 13:15
 **/
@Slf4j
public class NacosWritableDataSource<T> implements WritableDataSource<T> {


    private ConfigService configService = null;

    private String groupId;

    private String dataId;


    public NacosWritableDataSource(String serverAddr, String groupId, String dataId,
                                   String nameSpace) {
        this.groupId = groupId;
        this.dataId = dataId;
        Properties properties = buildProperties(serverAddr, nameSpace);
        try {
            this.configService = NacosFactory.createConfigService(properties);
        } catch (NacosException e) {
            log.error("[sentinel控制台配置持久化到nacos][初始化nacos客户端]失败,异常信息：{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public void write(T value) throws Exception {
        try {
            String convert = JSON.toJSONString(value);
            //持久化配置到nacos，每一次sentinel规则更新都会给到全量的配置信息
            configService.publishConfig(dataId, groupId, convert);
        } catch (NacosException e) {
            log.error("[sentinel控制台配置持久化到nacos][写入nacos]失败, 异常信息:{}", e.getMessage());
        }
    }

    @Override
    public void close() throws Exception {

    }

    private static Properties buildProperties(String serverAddr, String namespace) {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.setProperty(PropertyKeyConst.NAMESPACE, namespace);
        return properties;
    }
}

